package org.grow.took.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.grow.took.dao.DealBillDao;
import org.grow.took.dao.PlayerDao;
import org.grow.took.entity.*;
import org.grow.took.entity.enums.DealState;
import org.grow.took.exception.SeptemberException;
import org.grow.took.service.PlayerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDateTime;


//处理器 的统一异常处理
@RestController
@RequestMapping("/ceto/dealBill")
public class DealBillController {

    @Autowired
    private DealBillDao dealBillDao;
    @Autowired
    private PlayerDao playerDao;
    @Autowired
    private PlayerService playerService;
    //    交易 新增
//    dealBillId dealTime dealstate 后端生成 version=0
//    让一个用户的player表增加 另一个减少
//    8110772 8110792
    @PostMapping("/insert")
    public Boolean insert(@RequestBody DealBill dealBill) {
//        校验先省略
        dealBill.setDealBillId(0);
        dealBill.setDealState(DealState.willing);
        dealBill.setDealTime(LocalDateTime.now());
        dealBill.setVersion(0);
//        int insert = dealBillDao.insert(dealBill);
//        if (insert == 0) {
//            throw new RuntimeException("保存失败");
//        }
        Boolean r = null;
        try {
            r = playerService.txDeal(dealBill);
            if (r){
                dealBill.setDealState(DealState.succeeded);
            }
        } catch (Exception e) {
            dealBill.setDealState(DealState.failed);
            throw new SeptemberException("事务交易异常");
        }finally {
            int insert = dealBillDao.insert(dealBill);
        }
//        不要把异常当做敌人
//        异常是对方法返回值的补充
//        try catch异常后可以继续将异常抛出
//        抛出异常是对流程控制的一种重要手段
//        抛出异常意味着一个程序员认知到了问题的存在,但是不愿意花时间做出具体的解决方案
//        因为写代码的路途上,朝着一个目标前进,不宜被中途的琐事耽误了前进的思路 =>随手抛异常.
        return r;


    }

    @PostMapping("/query")
    public PagedResults<DealBill> query(
            @RequestBody DealBillSearchForm dealBillSearchForm){

        Integer pageNum = dealBillSearchForm.getPageNum();
        if (pageNum<=0){
            throw new SeptemberException("页数不能小于等于0");
        }
        Integer pageSize = dealBillSearchForm.getPageSize();
        IPage<DealBill> page = new Page<>(pageNum,pageSize);
//        IPage
        DealBillQueryCondition qc = dealBillSearchForm.getQueryCondition();
//        多条件where
        IPage<DealBill> dynamicQuery = dealBillDao.dynamicQuery(page, qc);

        PagedResults<DealBill> pagedResults = new PagedResults<>();
        pagedResults.setResults(dynamicQuery.getRecords());
        pagedResults.setTotal(dynamicQuery.getTotal());
        return pagedResults;

    }

}
